package com.sinoglobal.dumping.base;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.sinoglobal.dumping.exception.Dumpling_NoDataException;
import com.sinoglobal.wallet.util.LogUtils;
import com.sinoglobal.wallet.util.security.Encryption;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author ty
 * @createdate 2012-9-19 上午10:40:06
 * @Description: Http请求
 */
public class Dumpling_ConnectionUtil {
	private static String result = "";
//	private static final String URL = "http://192.168.10.146:8081/dumpling/";// 公网server地址
	private static final String URL = Dumpling_SinoConstans.INTERFACE_HOST;// 公网server地址
	private static final String NXHGQ__URL=Dumpling_SinoConstans.NXHGQ_LOGIN_URL;//正式

	private static final String ACCEPT = "Accept-Charset";
	private static final String UTF8 = "UTF-8";
	private static final String UTF8_ES = "UTF-8,*";
	private static final String CONNECTION_JSON = "json";
	private static final String APP_JSON = "APPLICATION/JSON";
	private static final String REQUEST_URL = "请求：URL:-->:";
	private static final String RESPONSE_STATUS = "响应状态码：";
	private static final String RESPONSE_PARAMS = "---返回的参数为--->>：";
	private static final String TERMINAL_ID = "terminalId";
	private static String name;

	private static Date serverDate; // 服务器时间

	public static Date getServerDate() {
		return serverDate;
	}

	private static String execute(HttpUriRequest req) throws Exception {
		long startTime = System.currentTimeMillis();

		String result = null;
		InputStream instream = null;
		try {
			HttpResponse response = executeLoad(req);
			if (response != null) {
				int statusCode = response.getStatusLine().getStatusCode();
				Dumpling_SinoLogUtil.i(RESPONSE_STATUS + statusCode);
				switch (statusCode) {
				case HttpStatus.SC_OK:
					result = EntityUtils.toString(response.getEntity(), UTF8);
					Dumpling_SinoLogUtil.i(Dumpling_ConnectionUtil.name + "-->result-->" + result);
					break;
				case HttpStatus.SC_FORBIDDEN: // 验证未通过
					break;
				case HttpStatus.SC_NOT_FOUND: // 请求错误
					break;
				}
			}
		} finally {
		}

		if (TextUtils.isEmpty(result)) {
			throw new Dumpling_NoDataException("request not data :" + req.getURI());
		}
		return result;
	}
	public static <T> T parseJson(String json,Class<T> clz){
		T t = null;
		try {
			t =  JSON.parseObject(json, clz);
		} catch (Exception e) {
			JSONObject jsonObject = null;
			try {
				jsonObject = new JSONObject(json);
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			if(jsonObject!=null){
				int code = jsonObject.optInt("code");
				String message = jsonObject.optString("message");
				t = invoke(code,message,clz);
			}
		}
		return t;
	}

	private static <T> T invoke(int code,String message,Class<T> clz){
		Method method1 = null,method2 = null;
		T t = null;
		try {
			t = clz.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		try {
			method1 = clz.getMethod("setCode",int.class);
			method2 = clz.getMethod("setMessage", String.class);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		if(method1!=null && method2!=null && t!=null){
			method1.setAccessible(true);
			method2.setAccessible(true);
			try {
				method1.invoke(t,code);
				method2.invoke(t,message);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		return t;
	}
	/**
	 * @author ty
	 * @createdate 2012-11-3 下午9:46:54
	 * @Description: 加载数据
	 * @param req
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws Exception
	 */
	public static HttpResponse executeLoad(HttpUriRequest req) throws IOException  {
		HttpClient httpclient = Dumpling_CustomerHttpClient.getInstance();
		req.addHeader(ACCEPT, UTF8_ES);
		HttpResponse response = httpclient.execute(req);
		return response;
	}

	/**
	 * 
	 * @author ty
	 * @createdate 2013-3-21 上午10:22:01
	 * @Description: post请求
	 * @param params
	 *            请求的参数封装
	 * @return
	 * @throws Exception
	 * 
	 */
	public static String post(Map<String, Object> params, String name)
			throws Exception {
		String URLNew = URL + name;
		Dumpling_ConnectionUtil.name = name;
		HttpPost httpost = new HttpPost(URLNew);
		String json = JSON.toJSONString(params);
		Dumpling_SinoLogUtil.i("请求的url为==" + URLNew);
		Dumpling_SinoLogUtil.i("SUBMIT" + json);
		Log.i("test", URLNew +"?json="+ json) ;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("json", json == null ? null : json));
		httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		return execute(httpost);
	}

	public static String postEncrptionDumpling(Map<String, Object> params, String name, String id,String key) throws Exception {
		String json1 = JSON.toJSONString(params);
		// 一下这句话是为了放置 用户输入“/”而造成的 非法字符。
		String json2 = json1.replace("/", "###");
		LogUtils.i("加密前===" + json2);
		Encryption.setSkey(key);
		String json3=Encryption.setEncryption(json2);
		LogUtils.i("加密后===="+json3);

		String URLNew = URL + name + URLEncoder.encode(URLEncoder.encode(json3, "UTF-8"), "UTF-8")+"&&tradeId="+id;
		//		LogUtils.i(REQUEST_URL + URLNew);
        LogUtils.i("发送的请求===" + URLNew);
		return httpRequest(new URL(URLNew));
	}
	private static String httpRequest(java.net.URL url) {
		try {

			// 第二步：获取HttpURLConnection对象
			HttpURLConnection huc = (HttpURLConnection) url.openConnection();
			huc.setRequestProperty("Accept", "application/json");
			huc.setRequestProperty("Content-Type", "application/json");
			// 第三步：设置请求超时时间
			huc.setConnectTimeout(30000);
			huc.setReadTimeout(30000);
			huc.setDoInput(true);
			huc.setDoOutput(true);
			// 设置 请求方式Get Post
			huc.setRequestMethod("POST");
			LogUtils.d("返回的响应码：" + huc.getResponseCode());
			// 第四步：获取响应吗，进行判断
			result = "";
			if (huc.getResponseCode() == 200) { // HTTP响应消息获取状态码
				BufferedReader in = new BufferedReader(new InputStreamReader(huc.getInputStream()));
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
				in.close();
				LogUtils.d( result);
				// System.out.println(result);
				String result1 = result.replace("###", "/");
				return result1;
			}
			huc.getOutputStream().flush();
			huc.getOutputStream().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 用于测试
	public static String postAllUrl(Map<String, Object> params, String url,String name) throws Exception {
		String URLNew =  url+name;
		Dumpling_ConnectionUtil.name = name;
		HttpPost httpost = new HttpPost(URLNew);
		String json = JSON.toJSONString(params);
		Dumpling_SinoLogUtil.i("请求的url为==" + URLNew);
		Dumpling_SinoLogUtil.i("SUBMIT" + json);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("json", json == null ? null : json));
		httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		return execute(httpost);
	}

	/**
	 *
	 * @author ty
	 * @createdate 2013-3-21 上午10:22:01
	 * @Description: post请求
	 * @param params
	 *            请求的参数封装
	 * @return
	 * @throws Exception
	 *
	 */
	public static String postNXHGQLogin(Map<String, Object> params)
			throws Exception {
		HttpPost httpost = new HttpPost(NXHGQ__URL);
		String json = JSON.toJSONString(params);
		Dumpling_SinoLogUtil.i("请求的url为==" + NXHGQ__URL);
		Dumpling_SinoLogUtil.i("SUBMIT" + json);
		Log.i("test", NXHGQ__URL +"===="+ json) ;
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("json", json == null ? null : json));
		httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		return execute(httpost);
	}
}
